package org.geektimes.projects.user.sql;


import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DataSourceManager {

    private DataSource dataSource;
    private static final DataSourceManager INSTANCE = new DataSourceManager();

    public void setDataSource(DataSource dataSource) {
        System.out.println("dataSource === " + dataSource.toString());
        DataSourceManager.INSTANCE.dataSource = dataSource;
    }

    public static DataSourceManager getInstance() {
//        initFromJNDI();
        return INSTANCE;
    }

//    private static void initFromJNDI() {
//        System.out.println("find JNDI DataSource...");
//        try {
//
//            Context context = new InitialContext();
//            INSTANCE.dataSource =  (DataSource) context.lookup("java:comp/env/jdbc/UserPlatformDB");
//            assert INSTANCE.dataSource != null;
//            System.out.println("connect to derby succuess");
//        } catch (NamingException e) {
//            e.printStackTrace();
//        }
//
//    }

//    private static void initFromCode() {
//        String databaseURL = "jdbc:derby:db/user-platform;create=true";
//        INSTANCE.dataSource = new BasicDataSource();
//        ((BasicDataSource) INSTANCE.dataSource).setUrl(databaseURL);
//    }

    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("连接数据库失败");
        }

    }
}
